/*
 * ====================================================================
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */
package com.cpe.wein.test;

import java.security.cert.CertificateException;
import java.util.List;

import javax.net.ssl.SSLContext;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.wechat.data.AccessToken;

import jodd.util.StringPool;

/**
 * This example demonstrates how to create secure connections with a custom SSL
 * context.
 */
public class ClientCustomSSL {

	public final static void main(String[] args) throws Exception {
		// 自定义的socket工厂类可以和指定的协议（Http、Https）联系起来，用来创建自定义的连接管理器。
		RegistryBuilder<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory> create();
		PlainConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
		// https信任所有证书
		SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
			@Override
			public boolean isTrusted(java.security.cert.X509Certificate[] chain, String authType)
					throws CertificateException {
				// TODO Auto-generated method stub
				return true;
			}
		}).build();
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
		r = r.register("https", sslsf);
		r = r.register("http", plainsf);
		// 连接池管理器
		PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(r.build());
		connectionManager.setMaxTotal(100);
		// cookie
		CookieStore cookieStore = new BasicCookieStore();

		HttpClientBuilder httpClientBuilder = HttpClients.custom().setConnectionManager(connectionManager)
				.setDefaultCookieStore(cookieStore);

		RequestConfig globalconfig = RequestConfig.custom().setRedirectsEnabled(true).setCookieSpec(CookieSpecs.DEFAULT)
				.build();

		CloseableHttpClient httpClient = httpClientBuilder.setDefaultRequestConfig(globalconfig).build();
		try {
			String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
			List<NameValuePair> params = Lists.newLinkedList();
			params.add(new BasicNameValuePair("appid", "wx641e16db3bd2bb02"));
			params.add(new BasicNameValuePair("secret", "685e63adcb43694099852eb8c4c5dc81"));

			URIBuilder uriBuilder = new URIBuilder(url);
			uriBuilder.addParameters(params);
			HttpGet httpget = new HttpGet(uriBuilder.build());
			CloseableHttpResponse response = httpClient.execute(httpget);
			try {
				HttpEntity entity = response.getEntity();
				String json = IOUtils.toString(entity.getContent(), StringPool.UTF_8);
				AccessToken accessToken = new Gson().fromJson(json, AccessToken.class);

				System.out.println("----------------------------------------");
				System.out.println(json);
				System.out.println(response.getStatusLine());
				System.out.println(accessToken);
				EntityUtils.consume(entity);
			} finally {
				response.close();
			}
		} finally {
			httpClient.close();
		}
	}

}
